package net.tensor.skynet.api.base

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.lang.reflect.GenericDeclaration
import java.lang.reflect.TypeVariable
import kotlin.math.ceil

@Suppress("UNCHECKED_CAST", "NAME_SHADOWING")
@Service
class QueryPage<T> {

    @Autowired
    private lateinit var mongoTemplate:MongoTemplate
    /**
     * MongDb分页公共方法
     * @param clazz 实体类的class对象
     * @param pageSize 每页的数量
     * @param pageNum 当前的页数
     * @param query query是啥不知道赶紧去查下，相当于sql语句
     * @return
     */
    fun pagination(clazz: Class<T>, pageSize: Int, pageNum: Int, query: Query): PageResult<T> {
        var pageNum = pageNum
        val total: Long? = clazz.let { this.mongoTemplate.count(query, it) }
        val pages = total?.toDouble()?.div(pageSize.toDouble())?.let { ceil(it).toInt() }
        if (pageNum <= 0 || pageNum > pages!!) {
            pageNum = 1
        }
        val skip = pageSize * (pageNum - 1)
        query.skip(skip.toLong()).limit(pageSize)
        val list: List<T> = mongoTemplate.find(query, clazz)
        val pageResult: PageResult<T> = PageResult()
        pageResult.total = total
        pageResult.pages = pages
        pageResult.pageSize = pageSize
        pageResult.pageNum = pageNum
        pageResult.list = list as ArrayList<T>
        return pageResult
    }

}